package com.web.exiaodao.remote.controller;
import com.web.exiaodao.business.entity.VideoViewRecord;
import com.web.exiaodao.remote.service.ApiMakeMoneyTableService;
import com.web.exiaodao.remote.service.ApiUserService;
import com.web.exiaodao.remote.service.ApiVideoViewRecordService;
import com.web.exiaodao.remote.vo.MakeMoneyTableVo;
import com.web.exiaodao.remote.vo.VideoViewRecordVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.YamlUtils;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.webstart.base.util.result.XaResult;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Title: ApiMakeMoneyTableController.java
 * @Package com.web.exiaodao.remote.controller
 * @Description: 签到-孝亲币管理信息接口
 * @author zhanglin
 * @date 2015年3月23日 下午1:00:00
 * @version V1.0
 */
@Api(value = "MakeMoneyTable", description = "签到-孝亲币管理接口", position = 10)
@Controller
@RequestMapping("/api/makeMoneyTable")
public class ApiMakeMoneyTableController extends BaseController {

	private static final Logger LOGGER = Logger.getLogger(ApiMakeMoneyTableController.class);

	@Autowired
	private ApiUserService userService;

	@Autowired
	private ApiMakeMoneyTableService makeMoneyTableService;

    @Autowired
    private ApiVideoViewRecordService video_view_recordService;

	/**
	 * @Title: findMakeMoneyTableList
	 * @Description: 查询所有签到-孝亲币管理信息
	 * @return    
	 */
	@ApiOperation(value="查询所有孝亲币信息列表",notes="查询所有签到-孝亲币管理信息,当返回的code=1时，取出object进行显示,存放为数组对象")
	@ResponseBody
	@RequestMapping(value="findMakeMoneyTableList",method=RequestMethod.POST)
	public XaResult<List<MakeMoneyTableVo>> findMakeMoneyTableList(
			@ApiParam("用户id,字段名:userId" ) @RequestParam(value = "userId" ) Long userId,
		@ApiParam("页号,字段名:nextPage,默认0,从第0页开始") @RequestParam(defaultValue = "0") Integer nextPage,
		@ApiParam("页长,字段名:pageSize,默认10") @RequestParam(defaultValue = "10") Integer pageSize,
        @ApiParam("赚钱还是消费（-1:消费；1:赚钱, 不填是所有）,字段名:consumeOrMakeMoney") @RequestParam(value = "consumeOrMakeMoney", required = false) Integer consumeOrMakeMoney
	) throws BusinessException{
        XaResult<List<MakeMoneyTableVo>> xr = new XaResult<>();
		if (XaUtil.isEmpty(userId)) {
			xr.error("用户Id不能为空！");
			return xr;
		}
		if (XaUtil.isEmpty(userService.validUserId(userId + ""))) {
			xr.error("用户Id不存在！");
			return xr;
		}

        if ( consumeOrMakeMoney != null &&  !(consumeOrMakeMoney == 1 | consumeOrMakeMoney == -1) ) {
            xr.error("consumeOrMakeMoney参数错误");
            return xr;
        }
		Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, "[{property:'createTime',direction:'DESC'}]");
        Map<String , Object> filterParams = WebUitl.getParametersStartingWith("{'search_EQ_userId':'" + userId + "'}", "search_");
        if (consumeOrMakeMoney != null) {
            filterParams = WebUitl.getParametersStartingWith(
            		"{'search_EQ_consumeOrMakeMoney':'" + consumeOrMakeMoney +"'" +
            		",'search_EQ_userId':'"+userId+"'}", "search_");
        }
        return makeMoneyTableService.findListEQStatusByFilter(XaConstant.Status.valid, filterParams, pageable);
	}

    /**
     * @Title: save 看视频，赚亲币；视频
     * @Description: 新增一条实体
     * @return
     */
    @ApiOperation(value="新增视频观看记录,赚钱亲币",notes="新增视频观看记录,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value="saveVideo_view_record",method=RequestMethod.POST)
    public XaResult<VideoViewRecordVo> saveVideoViewRecord(
            @ApiParam("观看人,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("观看时长(秒),字段名:duration") @RequestParam(value = "duration") Long duration,
            @ApiParam("机构id,字段名:institution_id") @RequestParam(value = "institution_id") Long institution_id,
            HttpServletRequest request
    ) throws BusinessException{
        XaResult<VideoViewRecordVo> xr = new XaResult<VideoViewRecordVo>();
        try{
            if (XaUtil.isEmpty(userId)) {
                xr.error("用户Id不能为空！");
                return xr;
            }
            if (XaUtil.isEmpty(userService.validUserId(userId + ""))) {
                xr.error("用户Id不存在！");
                return xr;
            }
            if (XaUtil.isEmpty(institution_id)) {
                xr.error("机构id不能为空！");
                return xr;
            }
            if (duration <= 0) {
                xr.error("观看时长不合法！");
                return xr;
            }

            //大于300s，算300s
            int videoDurationMaxInt = (int) YamlUtils.yaml2Map("data.yml").get("videoDurationMax");
            if (duration >= videoDurationMaxInt) {
                duration = Long.getLong(videoDurationMaxInt+"");
            }

            VideoViewRecord model = new VideoViewRecord();
            model.setUserId(userId);
            model.setDuration(duration.toString());
            model.setInstitutionId(institution_id);
            return video_view_recordService.createModel(model);
        }catch(Exception e){
            xr.error(e instanceof  BusinessException ? e.getMessage() : XaConstant.Message.error);
            LOGGER.error(XaConstant.Message.error + e.getMessage() , new Throwable(e));
        }
        return xr;
    }

}

